package com.example.backgroundmanger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.backgroundmanger.entity.Menu;
import com.example.backgroundmanger.mapper.MenuMapper;
import com.example.backgroundmanger.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2024-07-06
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    //注入持久层
    @Resource
    private MenuMapper menuMapper;

    //获取菜单
    @Override
    public List<Menu> getMenuService() {
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Menu::getParentId,0);
        //获取父菜单
        List<Menu> parentMenus = menuMapper.selectList(wrapper);
        //给父菜单设置子菜单
        setChildren(parentMenus);
        return parentMenus;
    }

    private void setChildren(List<Menu> parentMenus) {
        if(!parentMenus.isEmpty()){//如果父菜单不为空,则给父菜单添加子菜单
            for(Menu p:parentMenus){
                //查找该父菜单下的子菜单
                LambdaQueryWrapper<Menu> subWrapper = new LambdaQueryWrapper<>();
                subWrapper.eq(Menu::getParentId,p.getId());
                List<Menu> subMenus = menuMapper.selectList(subWrapper);
                //给父菜单设置子菜单
                p.setChildren(subMenus);
                //如果子菜单下还有子菜单,使用递归
                setChildren(subMenus);
            }
        }
    }
}
